package com.example.carrierapp.ui.main.dispatch.no

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.carrierapp.base.MVPBaseFragment
import com.example.carrierapp.bean.RowsBean
import com.example.carrierapp.config.gone
import com.example.carrierapp.config.show
import com.example.carrierapp.config.toast
import com.example.carrierapp.ui.adapter.CommonRecyclerAdapter
import com.example.carrierapp.ui.dialog.MAlertDialog
import com.example.carrierapp.ui.view.recycleview.HorizontalDividerDecoration
import com.example.carrierapp.ui.view.recycleview.WrapContentManager
import com.example.carrierapp.ui.view.recycleview.XRecyclerView
import com.example.carrierapp.util.*
import com.example.carrierapp.viewmodel.itemmodel.ItemDispatchModel
import com.example.lb.fingerdemo.R
import kotlinx.android.synthetic.main.item_dispatch_new.view.*
import kotlinx.android.synthetic.main.layout_recycleview.*
import kotlinx.android.synthetic.main.layout_search_bar.*

/**
 * 调度管理 - 运输中
 */
class DispatchNoFragment : MVPBaseFragment<DispatchNoContract.View, DispatchNoPresenter>(), XRecyclerView.LoadingListener, DispatchNoContract.View {

    private var mPage = 0
    private var mFilter = ""
    private var mLoadMore: Boolean = false

    private var receiver: BroadcastReceiver? = null

    private val adapter by lazy {
        CommonRecyclerAdapter<ItemDispatchModel>(context, R.layout.item_dispatch_new) { v, t, i ->
            if (i == 0 && SPUtils.getBoolean(context, "show_guide_1", false).not()) {
                t?.isGuide = true
            }
            v.to_top.setOnClickListener {
                t?.let { it ->
                    if (it.top)
                        mPresenter.cancelTop(it.id)
                    else
                        mPresenter.setTop(it.id)
                    it.top = it.top.not()
                }
            }
            v.confirm.setOnClickListener {
                MAlertDialog.Builder(context)
                        .setTitle("确认交货？")
                        .setMessage("交货后该计划不能再调度！")
                        .setPositiveButton("确认交货") { _, _ -> mPresenter.sureDelivery(t?.id ?: 0) }
                        .setNegativeButton("取消") { _, _ -> }
                        .create().show()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        LogUtil.d("DispatchNoFragment-1-")
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        LogUtil.d("DispatchNoFragment-2-")
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun onPause() {
        super.onPause()
        EditTextUtils.hideSoftKeyboard(activity)
    }

    override fun initView() {
        super.initView()
        et_dispatch_search.hint = "搜索装卸地/货主/货名/计划编码"
        initRecycleView()
    }

    override fun initData() {
        super.initData()
        showProgress()
        receiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                adapter.getItem(0)?.isGuide = false
            }
        }
        activity?.registerReceiver(receiver, IntentFilter("guide_end"))
        mPresenter.attachView(this)
        mPresenter.getDispatchList(mFilter, mPage)
    }

    override fun initEvent() {
        super.initEvent()
        ib_clear.setOnClickListener { et_dispatch_search.setText("") }
        et_dispatch_search.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                if (!TextUtils.isEmpty(et_dispatch_search.text.toString().trim { it <= ' ' })) {
                    ib_clear.visibility = View.VISIBLE
                } else {
                    ib_clear.visibility = View.GONE
                }
                mLoadMore = false
                mFilter = et_dispatch_search.text.toString().trim { it <= ' ' }
                mPage = 0
                mPresenter.getDispatchList(mFilter, mPage)
            }

            override fun afterTextChanged(s: Editable) {

            }
        })
    }

    private fun initRecycleView() {
        val mLinearLayoutManager = WrapContentManager(context, LinearLayoutManager.VERTICAL, false)
        recycler_view.layoutManager = mLinearLayoutManager
        recycler_view.addItemDecoration(HorizontalDividerDecoration(context, R.drawable.divider_horizontal_10_f3f6fa, DisplayUtil.dip2px(context, 10f)))
        recycler_view.setHasFixedSize(true)
        recycler_view.setLoadingMoreEnabled(true)
        recycler_view.setPullRefreshEnabled(true)
        recycler_view.setLoadingListener(this)
        recycler_view.refreshComplete()
        recycler_view.loadMoreComplete()

        recycler_view.adapter = adapter
    }

    override fun getLayout(): Int {
        return R.layout.fragment_dispatch_no
    }

    override fun createPresenter(): DispatchNoPresenter {
        return DispatchNoPresenter(context!!)
    }

    override fun onRefresh() {
        mFilter = ""
        mPage = 0
        mPresenter.getDispatchList(mFilter, mPage)
        mLoadMore = false
    }

    override fun onLoadMore() {
        mPage++
        mPresenter.getDispatchList(mFilter, mPage)
        mLoadMore = true
    }

    override fun getDispatchListSuccess(rows: RowsBean<ItemDispatchModel>) {
        dismissProgress()
        LogUtil.d("DispatchNoFragment-getDispatchListSuccess-$rows")
        rows.items?.let {
            ll_empty.gone()
            if (mLoadMore) {
                recycler_view.loadMoreComplete()
                adapter.insertData(it)
            } else {
                recycler_view.refreshComplete()
                adapter.refresh(it)
            }
            recycler_view.setNoMore(it.size < 10)
            ll_empty?.visibility = if (adapter.itemCount == 0) View.VISIBLE else View.GONE
        } ?: let {
            recycler_view.setNoMore(true)
            if (mLoadMore) {
                recycler_view.loadMoreComplete()
                ll_empty.gone()
            } else {
                recycler_view.refreshComplete()
                adapter.clear()
                ll_empty.show()
            }
        }
    }

    override fun getDispatchListFailde(msg: String) {
        dismissProgress()
        LogUtil.d("DispatchNoFragment-getDispatchListFailde-$msg")
        ToastUtils.showCenterToast(msg, context)
        if (recycler_view != null) {
            recycler_view.loadMoreComplete()
            recycler_view.refreshComplete()
        }
        ll_empty.visibility = if (adapter.itemCount == 0) View.VISIBLE else View.GONE
    }

    override fun onTopSuccess(isTop: Boolean) {
        toast(if (isTop) "置顶成功" else "取消置顶成功")
        onRefresh()
    }

    override fun sureDeliverySuccess(msg: String) {
        dismissProgress()
        ToastUtils.showCenterToast(context, "确认交货成功")
        onRefresh()
    }

    override fun sureDeliveryFailde(msg: String) {
        dismissProgress()
        ToastUtils.showCenterToast(context, msg)
    }

    override fun onDestroy() {
        super.onDestroy()
        receiver?.let { activity?.unregisterReceiver(it) }

    }

    companion object {

        fun newInstance(): DispatchNoFragment {
            return DispatchNoFragment()
        }
    }
}
